<?php
namespace Endpoints\CandyContent;

use Endpoints\Base\Endpoint;
use Endpoints\Tools\GetOssObject;
use Models\Candy\Content;
use Symfony\Component\Console\Input\InputArgument;

class IndexContent extends Endpoint
{
    // 定义参数
    const ARGUMENT_SEARCH   = 'search';
    const ARGUMENT_DATE_ID  = 'date_id';
    const ARGUMENT_MEDIA_TYPE = 'media_type';


    // 收参
    public function getArguments()
    {
        return [
            [static::ARGUMENT_SEARCH,InputArgument::OPTIONAL,'搜索项',''],
            [static::ARGUMENT_DATE_ID,InputArgument::OPTIONAL,'日期id',''],
            [static::ARGUMENT_MEDIA_TYPE,InputArgument::OPTIONAL,'媒体类型',1],
            [static::ARGUMENT_PAGE,InputArgument::OPTIONAL,'页数',1],
            [static::ARGUMENT_P_LIMIT,InputArgument::OPTIONAL,'获取多少数据','10'],
        ];
    }

    /**
     * 实现逻辑
     * @return \Laravelladder\Core\Collections\BaseCollection
     */
    public function dryRun()
    {
        $search = $this->argument(static::ARGUMENT_SEARCH);
        $dateId = $this->argument(static::ARGUMENT_DATE_ID);
        $page   = $this->argument(static::ARGUMENT_PAGE);
        $limit  = $this->argument(static::ARGUMENT_P_LIMIT);
        $offset = $limit * (($page > 0 ? $page : 1) - 1);
        $mediaType = $this->argument(static::ARGUMENT_MEDIA_TYPE);


        $sql = "SELECT
                    :select_columns
                FROM
                    hi_candy_content AS content
                LEFT JOIN hi_candy_calendar AS calendar ON content.date_id = calendar.id
                WHERE
                    content.deleted_at IS NULL ";

        if($search) $sql .= "AND (content.title like :search or content.description like :search) ";
        if($dateId) $sql .= "AND content.date_id = :dateId ";
        if($mediaType) $sql .= "AND content.file_type = :fileType ";

        $sql .= " :order_by :pagination ";

        $list = $this
            ->getUniRepo()
            ->sqlSelectListWithPagination(
                $sql,
                [
                    'search'    => '%'.$search.'%',
                    'dateId'    => $dateId,
                    'fileType'  => $mediaType,
                ],
                [
                    'content.*,calendar.date',
                ],
                $limit,
                $offset,
                ['content.sort'=>'asc','content.id'=>'asc']
                );

        $list->each(function($item){
            /**
             * @var $item \Laravelladder\Core\Models\UniModel
             */
            $objUrl = GetOssObject::getInstance()->setArguments([
                GetOssObject::ARGUMENT_FILE_ID => $item->{Content::DB_FIELD_FILE_VALUE},
                GetOssObject::ARGUMENT_IMG_OPTION => 'image/resize,m_lfit,h_500,w_500',
            ])->dryRun();
            $item->addFillable('obj_url',$objUrl);
        });
        return $list;
    }
}